﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ManagedWinapi.Windows;

namespace wutils
{
    public partial class TaskStrip : Form
    {
        public TaskStrip()
        {
            InitializeComponent();
            Initialize();
        }

        private void Initialize()
        {
            WindowUtils.MinimizedWindowsChanged += MinimizeWindowChanged;
            KeyDown += TaskStrip_KeyDown;
        }

        void TaskStrip_KeyDown(object sender, KeyEventArgs e)
        {
            if (!e.Alt) return;

            if (FormBorderStyle == FormBorderStyle.SizableToolWindow)
                FormBorderStyle = FormBorderStyle.None;
            else
                FormBorderStyle = FormBorderStyle.SizableToolWindow;
        }

        private void MinimizeWindowChanged(object sender, WindowEventArgs e)
        {
            if (e.Action != EventAction.ADDED) return;

            container.Controls.Add(new MinimizedWindowButton(e.Window, container));
        }

        public void Rebuild()
        {
            if (container.Controls.OfType<MinimizedWindowButton>().Count() == WindowUtils.MinimizedWindows.Count())
                return;

            var btns = new List<MinimizedWindowButton>(container.Controls.OfType<MinimizedWindowButton>());
            foreach (var btn in btns)
            {
                container.Controls.Remove(btn);
            }
            var windows = new List<SystemWindow>(WindowUtils.MinimizedWindows);
            foreach (var window in windows)
            {
                container.Controls.Add(new MinimizedWindowButton(window, container));
            }
        }

        public void Destroy()
        {
            List<MinimizedWindowButton> btns = new List<MinimizedWindowButton>();
            btns.AddRange(container.Controls.OfType<MinimizedWindowButton>());

            foreach (var btn in btns)
            {
                btn.Destroy();
            }
            Dispose();
        }
    }
}
